<?php 
class ControllerSurveySurvey extends Controller {
	private $error = array();
	
	public function index() {
		
		$this->language->load('survey/survey');
		
		$this->load->model('survey/survey');
		
		if (isset($this->request->get['survey_id'])) {
			$survey_id = $this->request->get['survey_id'];
		} else {
			$survey_id = 0;
		}
		
		$survey_info = $this->model_survey_survey->getSurvey($survey_id);
		
//		print_r($survey_info);
		
		if(!isset($this->session->data['email'])) {
			if($survey_info['login'] == 'N') {
				if(isset($this->request->get['token']))
					$this->session->data['email'] = $this->request->get['token'];
				else {
					$token = base64_encode($_SERVER['REMOTE_ADDR']."|".date('Y-m-d H:i:s'));
					$this->session->data['email'] = $token;				
				}
			}
		}
				
		if(!isset($this->session->data['email'])) {
			$this->session->data['redirect_here'] = $this->url->link('survey/survey', 'survey_id=' . $this->request->get['survey_id'], 'SSL');
	  
	  		$this->redirect($this->url->link('account/login', '', 'SSL'));
		}
		
		$this->data['breadcrumbs'] = array();
		
      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home'),
        	'separator' => false
      	);
		
		if ($survey_info) {
	  		$this->document->setTitle($survey_info['title']); 

      		$this->data['breadcrumbs'][] = array(
        		'text'      => $survey_info['title'],
				'href'      => $this->url->link('survey/survey', 'survey_id=' .  $survey_id),      		
        		'separator' => $this->language->get('text_separator')
      		);
						
      		$this->data['heading_title'] = $survey_info['title'];
      		
      		$this->data['button_start'] = $this->language->get('button_start');
			
			$this->data['description'] = html_entity_decode($survey_info['description'], ENT_QUOTES, 'UTF-8');
      		
      		if($survey_info['mode'] == 'P') {
      			$all_questions = array();
      			
      			if (isset($this->request->get['survey_id'])) {
					$filter_survey_id = $this->request->get['survey_id'];
				} else if (isset($this->request->get['filter_survey_id'])) {
					$filter_survey_id = $this->request->get['filter_survey_id'];
				} else if(isset($this->session->data['survey_id'])) {
					$filter_survey_id = $this->session->data['survey_id'];
				} else {
					$filter_survey_id = '0';		
				}
				
				if (isset($this->request->get['sort'])) {
					$sort = $this->request->get['sort'];
				} else {
					$sort = 'p.sort_order';
				} 
		
				if (isset($this->request->get['order'])) {
					$order = $this->request->get['order'];
				} else {
					$order = 'ASC';
				}
		  		
				if (isset($this->request->get['page'])) {
					$page = $this->request->get['page'];
				} else {
					$page = 1;
				}
				
				if (isset($this->request->get['limit'])) {
					$limit = $this->request->get['limit'];
				} else {
					$limit = $this->config->get('config_catalog_limit');
				}
      			
      			$data = array(
					'filter_survey_id'  => $filter_survey_id, 
					'sort'                => $sort,
					'order'               => $order,
//					'start'               => ($page - 1) * $limit,
//					'limit'               => $limit
				);
				
				$this->load->model('survey/question');
				
				$all_questions = $this->model_survey_question->getQuestions($data);
				
				$this->load->model('localisation/language');			
				$language_id = $this->model_localisation_language->getLanguageByCode($this->session->data['language']);
				$language_id = $language_id['language_id'];
				$customer_id = $this->customer->getId();				
				
				if(isset($this->session->data['guest_id']))
					$guest_id = $this->session->data['guest_id'];
				else
					$guest_id = 0;
				
				if($this->request->server['REQUEST_METHOD'] == "POST") {
					
					foreach($all_questions as $question_id => $question_info) {
								
						$data = array(
							'email' => $this->session->data['email'],
							'survey_id' => $question_info['survey_id'],
							'guest_id' => $guest_id,
							'customer_id' => $customer_id,
							'question_id' => $question_id,
							'language_id' => $language_id,
						);					
						
						$check_answer = $this->model_survey_question->checkAnswer($data);
					
						if($this->validateForm($question_info)) {

							$time_took = strtotime(date('Y-m-d H:i:s')) - strtotime($this->session->data['start_time']);
														
//							echo $question_id." | ";
							
							if(isset($this->request->post['answer_'.$question_id])) {
								$answer = $this->request->post['answer_'.$question_id];
								if(is_array($answer)) {
									
									if(count($check_answer) > 0) {											
											$this->model_survey_question->deleteAnswers($data);
									}
									
									foreach($answer as $each_option) {
										$data = array (
											'email' => $this->session->data['email'],
											'survey_id' => $question_info['survey_id'],
											'guest_id' => $guest_id,
											'customer_id' => $customer_id,
											'question_id' => $question_id,
											'language_id' => $language_id,
											'answer' => $each_option,
											'ip' => $this->request->server['REMOTE_ADDR'],
											'time_took' => $time_took,
											'date_added' => date("Y-m-d H:i:s"),
											'date_modified' => date("Y-m-d H:i:s")
										);

										$this->model_survey_question->addAnswer($data);
									}
								} else {
									$data = array(
										'email' => $this->session->data['email'],
										'survey_id' => $question_info['survey_id'],
										'guest_id' => $guest_id,
										'customer_id' => $customer_id,
										'question_id' => $question_id,
										'language_id' => $language_id,
										'answer' => $answer,
										'ip' => $this->request->server['REMOTE_ADDR'],
										'time_took' => $time_took,
										'date_added' => date("Y-m-d H:i:s"),
										'date_modified' => date("Y-m-d H:i:s")
									);
									
									if(count($check_answer) > 0) {
										$data['answer_id'] = $check_answer['answer_id'];
										$this->model_survey_question->editAnswer($data);
									} else {
										$this->model_survey_question->addAnswer($data);						
									}	
								}	
								
//								print_r($data);
							}
						}
						
						if (isset($this->error[$question_id])) {
							$this->error['question'][$question_id] = $this->error[$question_id];
						}						
					}
					
					if ($this->error && !isset($this->error['warning'])) {
						$this->error['warning'] = $this->language->get('error_warning');
					}
			  		
			  		if (!$this->error) {
						$this->redirect($this->url->link('survey/survey/finished', 'survey_id=' .  $question_info['survey_id']));
					}
				}
				
//				print_r($this->error);
				
				foreach($all_questions as $question_id => $question_info) {
					
					$data = array(
						'email' => $this->session->data['email'],
						'survey_id' => $question_info['survey_id'],
						'guest_id' => $guest_id,
						'customer_id' => $customer_id,
						'question_id' => $question_id,
						'language_id' => $language_id,
					);					
					
					$check_answer = $this->model_survey_question->checkAnswer($data);
					
					$question_num = "";
					if(!empty($question_info['qnum']))
						$question_num = $question_info['qnum']." ";
					
					$all_questions[$question_id]['question_id'] = $question_id; 
					$all_questions[$question_id]['heading_title'] = $question_num.nl2br($question_info['title']);
					$all_questions[$question_id]['qtype'] = $question_info['qtype'];
					$all_questions[$question_id]['qformat'] = $question_info['qformat'];
					
					$options = array();
					switch ($question_info['qtype']) {
		      			case 'radio' :
				      		$question_info['lable'] = str_replace("\r","", $question_info['lable']);
				      		$all_lables = explode("\n", $question_info['lable']);
				      		if(!empty($question_info['value'])) {
				      			$question_info['value'] = str_replace("\r","", $question_info['value']);
				      			$all_values = explode("\n", $question_info['value']);
				      		} else {
				      			$all_values = $all_lables;
				      		}      			
				      		
				      		$default_value = 0;
				      		if(isset($this->request->post['answer_'.$question_id])) {
//				      			echo "1";
				      			if(!empty($this->request->post['answer_'.$question_id]))
				      				$default_value = $this->request->post['answer_'.$question_id];
				      		} else if(!empty($check_answer['answer'])) {
//				      			echo "2";
				      			$default_value = $check_answer['answer'];
				      		} else if(!empty($question_info['default'])) {
//				      			echo "3";
				      			$default_value = $question_info['default'];
				      		}				      			
				      		
				      		
//				    		echo $default_value." | ".$question_id." # ";
//				    		print_r($all_values);
				      		
				      		
				      		foreach($all_lables as $key => $each_value) {
				      			      			
				      			$default = 0;
				      			
				      			if($default_value == $all_values[$key]) {
				      				$default = 1;
				      			}				      				
				      			
				      		    $options[] = array(
					      			'lable' => $all_lables[$key],
					      			'value' => $all_values[$key],
					      			'default' => $default
					      		);	
//					      		
				      		}   
		      			break;
		      			case 'checkbox' :
		      				$check_answer = $this->model_survey_question->checkAnswers($data);
		      				
				      		$question_info['lable'] = str_replace("\r","", $question_info['lable']);
				      		$all_lables = explode("\n", $question_info['lable']);
				      		if(!empty($question_info['value'])) {
				      			$question_info['value'] = str_replace("\r","", $question_info['value']);
				      			$all_values = explode("\n", $question_info['value']);
				      		} else {
				      			$all_values = $all_lables;
				      		}      			
				      		
				      		$default_value = array();
				      		if(isset($this->request->post['answer_'.$question_id])) {
//				      			echo "1";
				      			if(!empty($this->request->post['answer_'.$question_id]))
				      				$default_value = $this->request->post['answer_'.$question_id];
				      		} else if(count($check_answer) > 0) {
//				      			echo "2";
								foreach($check_answer as $each_option) {
									$default_value[] = $each_option['answer'];
								}
				      		} else if(!empty($question_info['default'])) {
//				      			echo "3";
				      			$default_value = explode("\n", $question_info['default']);
				      		}				      			
				      		
				      		
//				    		print_r($default_value);
//				    		print_r($all_values);
				    		
				      		
				      		foreach($all_lables as $key => $each_value) {
				      			      			
				      			$default = 0;
				      			
				      			if(in_array($all_values[$key], $default_value)) {
				      				$default = 1;
				      			}				      				
				      			
				      		    $options[] = array(
					      			'lable' => $all_lables[$key],
					      			'value' => $all_values[$key],
					      			'default' => $default
					      		);	
				      		}      			
		      			break;
		      			case 'text' :
							$options = array(
				      			'lable' => $question_info['lable'],
				      			'value' => $question_info['value'],
				      			'default' => $question_info['default']
				      		);      					
		      			break;
		      			case 'textarea' :
							$options = array(
				      			'lable' => $question_info['lable'],
				      			'value' => $question_info['value'],
				      			'default' => $question_info['default']
				      		);      					
		      			break;
		      		}
		      		
//		      		print_r($options);
		      		
		      		$all_questions[$question_id]['options'] = $options;
		      		$all_questions[$question_id]['description'] = html_entity_decode($question_info['description'], ENT_QUOTES, 'UTF-8');
      				      		 
				}
      			
      			$this->data['action'] = $this->url->link('survey/survey', 'survey_id=' . $survey_id);
      			
      			$this->data['all_questions'] = $all_questions;
      			
      			$this->data['button_submit'] = $this->language->get('button_submit');

      			$this->data['submit'] = "javascript:$('#form').submit();";
      			
//      			print_r($all_questions);
      			
      			$this->data['all_questions'] = $all_questions;
      		} else {
      			$this->data['start'] = $this->url->link('survey/survey/start', 'survey_id=' .  $survey_id);	
      		}
      		
      		if(isset($this->error['warning'])) {
      			$this->data['error_warning'] = $this->error['warning']; 	
      		} else {
      			$this->data['error_warning'] = "";
      		}
      		
      		if (isset($this->session->data['success'])) {
				$this->data['success'] = $this->session->data['success'];
			
				unset($this->session->data['success']);
			} else {
				$this->data['success'] = "";
			}
      		
      		if(isset($this->error['question'])) {
      			$this->data['error_question'] = $this->error['question']; 	
      		} else {
      			$this->data['error_question'] = array();
      		}

			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/survey/survey.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/survey/survey.tpl';
			} else {
				$this->template = 'default/template/survey/survey.tpl';
			}
			
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
			
			$this->session->data['start_time'] = date('Y-m-d H:i:s');
			
	  		$this->response->setOutput($this->render());
    	} else {
      		$this->data['breadcrumbs'][] = array(
        		'text'      => $this->language->get('text_error'),
				'href'      => $this->url->link('survey/survey', 'survey_id=' . $survey_id),
        		'separator' => $this->language->get('text_separator')
      		);
				
	  		$this->document->setTitle($this->language->get('text_error'));
			
      		$this->data['heading_title'] = $this->language->get('text_error');

      		$this->data['text_error'] = $this->language->get('text_error');

      		$this->data['button_continue'] = $this->language->get('button_continue');

      		$this->data['continue'] = $this->url->link('common/home');

			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/error/not_found.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/error/not_found.tpl';
			} else {
				$this->template = 'default/template/error/not_found.tpl';
			}
			
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
					
	  		$this->response->setOutput($this->render());
    	}
  	}
  	
  	public function finished() {
  		$survey_id = $this->request->get['survey_id'];
  		unset($this->session->data['survey_id']);
  		
  		$this->language->load('survey/survey');
		
		$this->load->model('survey/survey');
		
		$survey_info = $this->model_survey_survey->getSurvey($survey_id);
//  		print_r($survey_info);
  		
  		$this->document->setTitle($survey_info['title']); 

		$this->data['breadcrumbs'] = array();
		
      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home'),
        	'separator' => false
      	);
      	
  		$this->data['breadcrumbs'][] = array(
    		'text'      => $survey_info['title'],
			'href'      => $this->url->link('survey/survey', 'survey_id=' .  $survey_id),      		
    		'separator' => $this->language->get('text_separator')
  		);
  		
  		if(isset($this->error['warning'])) {
  			$this->data['error_warning'] = $this->error['warning']; 	
  		} else {
  			$this->data['error_warning'] = "";
  		}
  		
  		if (isset($this->session->data['success'])) {
			$this->data['success'] = $this->session->data['success'];
		
			unset($this->session->data['success']);
		} else {
			$this->data['success'] = $this->language->get('text_success');
		}		
					
  		$this->data['heading_title'] = $survey_info['title'];
  		
		$this->data['description'] = html_entity_decode($survey_info['closing'], ENT_QUOTES, 'UTF-8');		
		
  		
  		$this->data['button_start'] = $this->language->get('button_continue');  		
		
		if(isset($this->session->data['survey_ides'])) {
			$all_tests = explode(",", $this->session->data['survey_ides']);
			$survey_key = array_search($survey_id, $all_tests); 
			$survey_id = $all_tests[($survey_key + 1)];
			if(!empty($survey_id))
				$this->data['start'] = $this->url->link('survey/survey', 'survey_id=' . $survey_id, 'SSL');
			else
				$this->data['start'] = $this->url->link('common/home');
		} else {
			$all_tests = array();
			$this->data['start'] = $this->url->link('common/home');
		}		
		

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/survey/survey.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/survey/survey.tpl';
		} else {
			$this->template = 'default/template/survey/survey.tpl';
		}
		
		$this->children = array(
			'common/column_left',
			'common/column_right',
			'common/content_top',
			'common/content_bottom',
			'common/footer',
			'common/header'
		);
					
  		$this->response->setOutput($this->render());
  	}
  	
  	public function start() {
  		$survey_id = $this->request->get['survey_id'];
  		$this->session->data['survey_id'] = $survey_id;  		
  		
  		$this->load->model('survey/question');
  		$survey_questions = $this->model_survey_question->getSurveyQuestions($survey_id);
  		$question_id = $survey_questions['0'];
  		
  		$this->redirect($this->url->link('survey/question', 'question_id=' . $question_id));
  		exit;
  	}
  	
  	public function validateForm($question_info = array()) {
  		
  		$question_id = $question_info['question_id'];
  		$question_qtype = $question_info['qtype'];
  		
  		if($question_info['required']) {
  			
  			if(empty($this->request->post['answer_'.$question_id]))	
  				$this->error[$question_id] = $this->language->get('error_'.$question_qtype);
  		}
  		
  		if (!isset($this->error[$question_id])) {
			return true;
		} else {
			return false;
		}
  	}
	
	public function info() {
		$this->load->model('survey/survey');
		
		if (isset($this->request->get['survey_id'])) {
			$survey_id = $this->request->get['survey_id'];
		} else {
			$survey_id = 0;
		}      
		
		$survey_info = $this->model_survey_survey->getSurvey($survey_id);

		if ($survey_info) {
			$output  = '<html dir="ltr" lang="en">' . "\n";
			$output .= '<head>' . "\n";
			$output .= '  <title>' . $survey_info['title'] . '</title>' . "\n";
			$output .= '  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' . "\n";
			$output .= '</head>' . "\n";
			$output .= '<body>' . "\n";
			$output .= '  <br /><br /><h1>' . $survey_info['title'] . '</h1>' . "\n";
			$output .= html_entity_decode($survey_info['description'], ENT_QUOTES, 'UTF-8') . "\n";
			$output .= '  </body>' . "\n";
			$output .= '</html>' . "\n";			

			$this->response->setOutput($output);
		}
	}
}
?>